package com.kly.pay.service.impl;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.AndroidPublisherScopes;
import com.kly.pay.factory.GoogleApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;

/**
 * @author linqu
 */
@Slf4j
@Service("mebooGoogleApi")
public class MebooGoogleApiImpl implements GoogleApiService {
    /**
     * 接入凭证
     */
    @Value("${google.pay.auth.credential}")
    private String googlePayCredential;
    /**GoogleFactorySingleton
     * 一次性商品
     */
    private AndroidPublisher.Purchases.Products products;
    /**
     * 订阅api_v2
     */
    private AndroidPublisher.Purchases.Subscriptionsv2 subscriptionsv2;
    /**
     * 订阅api
     */
    private AndroidPublisher.Purchases.Subscriptions subscriptions;

    @PostConstruct
    public void initGooglePay() {
        try {
            // createScoped给令牌访问权限设置使用的权限范围
            GoogleCredential credential = GoogleCredential.fromStream(new ByteArrayInputStream(googlePayCredential.getBytes()))
                    .createScoped(AndroidPublisherScopes.all());
            if(credential==null) {
                log.error("==========>Get GoogleCredential fails 获取谷歌凭证失败！");
            }
            HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            JacksonFactory jacksonFactory = JacksonFactory.getDefaultInstance();
            AndroidPublisher publisher = new AndroidPublisher.Builder(httpTransport, jacksonFactory, credential).build();
            this.products = publisher.purchases().products();
            this.subscriptions = publisher.purchases().subscriptions();
            this.subscriptionsv2 = publisher.purchases().subscriptionsv2();

        }  catch (Exception e) {
            log.error("==========>Init GoogleCredential failed", e);
        }
    }

    @Override
    public String getPackageName() {
        return "com.kly.meboo";
    }
    @Override
    public AndroidPublisher.Purchases.Products getProducts() {
        return this.products;
    }
    @Override
    public AndroidPublisher.Purchases.Subscriptions getSubscriptions() {
        return this.subscriptions;
    }
    @Override
    public AndroidPublisher.Purchases.Subscriptionsv2 getSubscriptionsv2() {
        return this.subscriptionsv2;
    }
}
